#!/bin/bash

# 第三方服务配置脚本
set -e

echo "配置第三方服务..."

# 检查必要的环境变量
check_env_var() {
    if [ -z "${!1}" ]; then
        echo "警告: 环境变量 $1 未设置"
        return 1
    else
        echo "✓ $1 已配置"
        return 0
    fi
}

echo "检查环境变量配置..."

# 检查数据库配置
echo "检查数据库配置..."
check_env_var "MYSQL_ROOT_PASSWORD"
check_env_var "MYSQL_DATABASE"
check_env_var "MYSQL_USER"
check_env_var "MYSQL_PASSWORD"

# 检查Redis配置
echo "检查Redis配置..."
check_env_var "REDIS_HOST"

# 检查JWT配置
echo "检查JWT配置..."
check_env_var "JWT_SECRET"

# 检查OSS配置
echo "检查阿里云OSS配置..."
check_env_var "OSS_ACCESS_KEY_ID"
check_env_var "OSS_ACCESS_KEY_SECRET"
check_env_var "OSS_BUCKET"
check_env_var "OSS_REGION"

# 检查微信配置
echo "检查微信小程序配置..."
check_env_var "WECHAT_APP_ID"
check_env_var "WECHAT_APP_SECRET"

# 检查短信配置
echo "检查短信服务配置..."
check_env_var "SMS_ACCESS_KEY_ID"
check_env_var "SMS_ACCESS_KEY_SECRET"
check_env_var "SMS_SIGN_NAME"

# 测试OSS连接
echo "测试阿里云OSS连接..."
node -e "
const OSS = require('ali-oss');
const client = new OSS({
  region: process.env.OSS_REGION,
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  bucket: process.env.OSS_BUCKET
});

client.listBuckets().then(result => {
  console.log('✓ OSS连接成功');
}).catch(err => {
  console.log('✗ OSS连接失败:', err.message);
});
"

# 测试微信API
echo "测试微信API连接..."
node -e "
const axios = require('axios');

axios.get('https://api.weixin.qq.com/cgi-bin/token', {
  params: {
    grant_type: 'client_credential',
    appid: process.env.WECHAT_APP_ID,
    secret: process.env.WECHAT_APP_SECRET
  }
}).then(response => {
  if (response.data.access_token) {
    console.log('✓ 微信API连接成功');
  } else {
    console.log('✗ 微信API连接失败:', response.data);
  }
}).catch(err => {
  console.log('✗ 微信API连接失败:', err.message);
});
"

# 创建必要的目录
echo "创建必要的目录..."
mkdir -p backend/logs
mkdir -p backend/uploads
mkdir -p nginx/logs
mkdir -p nginx/ssl

# 设置目录权限
echo "设置目录权限..."
chmod 755 backend/logs
chmod 755 backend/uploads
chmod 755 nginx/logs
chmod 700 nginx/ssl

echo "第三方服务配置完成！"